//
//  MSUserCenterController.m
//  MSJD
//
//  Created by xiangbo on 2018/9/5.
//  Copyright © 2018 xiangbo. All rights reserved.
//

#import "MSUserCenterController.h"

#import "MSPhoneLoginController.h"
#import "MSSecurityViewController.h"
#import "MSUserDetailViewController.h"
#import "MSMainViewController.h"

#import "MSUserCenterCell.h"

#import "AppDelegate.h"

/** 自定义用户中心cell类型 */
typedef NS_ENUM(NSInteger, MSUserCenterCellType) {
    MSUserCenterCellTypeSecurity = 0, // 安全设置
//    MSUserCenterCellTypeStore, // 收藏
    MSUserCenterCellTypeMechantEnter, // 商家入驻
    MSUserCenterCellTypeService = 3, // 联系客服
    MSUserCenterCellTypeCache, // 清除缓存
    MSUserCenterCellTypeVersion, // 版本号
    MSUserCenterCellTypeAbount // 关于门秀
};

@interface MSUserCenterController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *tableHeadView;
@property (nonatomic, strong) UIView *bufferView;
@property (nonatomic, strong) UIImageView *bufferIcon; // 高斯模糊图片
@property (nonatomic, strong) UIImageView *headIcon;
@property (nonatomic, strong) UILabel *userNameLabel;

@property (nonatomic, strong) UIView *tableFootView;

@property (nonatomic, strong) UIButton *mailButton;

@property (nonatomic, copy) NSArray *dataSource;

@end

@implementation MSUserCenterController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = rgba(0, 0, 0, 0.05);
    
    [self initSubViews];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [self reloadUserInfo];
    [self.tableView reloadData];
}
/** 重设用户信息 */
- (void)reloadUserInfo {
    MSUser *loginUser = [UserAccesser loadAccount];
    self.userNameLabel.text = [MSSafeObject isNull:loginUser.username]?@"未知":loginUser.username;
    [self.headIcon setImageWithURL:[NSURL URLWithString:[MSSafeObject stringInfo:loginUser.avatar]] placeholder:[UIImage imageNamed:@"account_default"]];
    [self.bufferIcon setImageWithURL:[NSURL URLWithString:[MSSafeObject stringInfo:loginUser.avatar]] placeholder:[UIImage imageNamed:@"account_default"]];
}

- (void)initSubViews {
    
    self.dataSource = @[@"安全设置", @"商家入驻", @"", @"联系客服", @"清除缓存", @"版本号", @"关于门秀"];
    
    [self.view addSubview:self.tableView];
    CGFloat statusBarHeight = MS_STATUS_HEIGHT;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.offset(0);
        make.top.offset(-statusBarHeight);
    }];
    self.tableView.tableHeaderView = self.tableHeadView;
    self.tableView.tableFooterView = self.tableFootView;
    
    // 添加背景Icon
    UIImageView *bufferIcon = [[UIImageView alloc] init];
    [self.bufferView addSubview:bufferIcon];
    [bufferIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.right.offset(0);
    }];
    self.bufferIcon = bufferIcon;
    // 添加高斯模糊
    UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc]initWithEffect:effect];
//    effectView.backgroundColor = rgba(0, 0, 0, 0.3);
    [self.bufferView addSubview:effectView];
    [effectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.right.offset(0);
    }];
    
    // 消息按钮
    [self.view addSubview:self.mailButton];
    CGFloat mailX = 10;
    CGFloat mailY = 20;
    CGFloat mailWidth = 44;
    [self.mailButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(mailY);
        make.left.offset(mailX);
        make.width.height.offset(mailWidth);
    }];
}

- (void)initNotifications {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveLoginSuccessMessage:) name:MSUserLoginSuccessNotification object:nil];
}

#pragma mark - Notifications
/** 收到登录成功的消息 */
- (void)receiveLoginSuccessMessage:(NSNotification *)notification {
    [self reloadUserInfo];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count; // 8行有数据的cell 2行空白cell
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 2) {
        UITableViewCell *emptyCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"emptyCell"];
        emptyCell.contentView.backgroundColor = [UIColor clearColor];
        emptyCell.backgroundColor = [UIColor clearColor];
        return emptyCell;
    }
    MSUserCenterCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MSUserCenterCell"];
    
    NSString *tip = self.dataSource[indexPath.row];
    NSString *rightValue = @"";
    if (indexPath.row == MSUserCenterCellTypeCache) {
        // 清除缓存cell
        rightValue = [NSString stringWithFormat:@"%.2fM", [self folderSize]];
    } else if (indexPath.row == MSUserCenterCellTypeVersion) {
        // 版本号cell
        rightValue = [DeviceInfo getBigVersion];
    }
    [cell refreshUserCenterCellWithTitle:tip rightValue:rightValue row:indexPath.row];
    
    return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.row) {
        case MSUserCenterCellTypeSecurity:
        { // 安全设置
            [self presentToSecurityViewController];
        }
            break;
        case MSUserCenterCellTypeMechantEnter:
        { // 商家入驻
            [self presentToBusinessEnterViewController];
        }
            break;
        case MSUserCenterCellTypeService:
        { // 联系客服
            [self contactCustomerService];
        }
            break;
        case MSUserCenterCellTypeCache:
        { // 清除缓存
            [self clearCaches];
        }
            break;
        case MSUserCenterCellTypeVersion:
        { // 版本号
        }
            break;
        case MSUserCenterCellTypeAbount:
        { // 关于
        }
            break;
        default:
            break;
    }
    NSLog(@"点击了第%ld个cell", indexPath.row);
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 2) {
        return 10;
    }
    return 50;
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat space = 20;
    CGFloat targetOffsetY = 210 - MS_STATUS_HEIGHT - 20 - 44;
    CGFloat scrollViewContentOffsetY = scrollView.contentOffset.y;
    if (scrollViewContentOffsetY < -20) {
        CGFloat bufferIconY = scrollViewContentOffsetY + 20;
        self.bufferView.frame = CGRectMake(0, scrollViewContentOffsetY, MS_SCREEN_WIDTH, -bufferIconY + 20 + 210);
    }
    if (scrollViewContentOffsetY > targetOffsetY) {
        if (!self.mailButton.hidden) {
            self.mailButton.hidden = YES;
        }
    } else if (scrollViewContentOffsetY < targetOffsetY - space) {
        if (self.mailButton.hidden) {
            self.mailButton.hidden = NO;
        }
        CGFloat newAlpha = ((targetOffsetY - space) - scrollViewContentOffsetY) / 20.0;
        self.mailButton.alpha = newAlpha;
    }
}

#pragma mark - Event Response
/** 退出登录按钮点击 */
- (void)logOutButtonClick:(UIButton *)sender {
    // 删除账号信息
    [UserAccesser deleteAccount];
    // 发送退出登录消息
    [[NSNotificationCenter defaultCenter] postNotificationName:MSUserLogOutNotification object:nil];
    
    // 切换tabbar
    [[MSMainViewController sharedInstance] setSelectedIndex:0];
}
/** 消息按钮点击 */
- (void)mailButtonClick:(UIButton *)sender {
    
}
/** 头部图片点击 */
- (void)headIconClick {
    MSUserDetailViewController *userDetailVC = [MSUserDetailViewController loadUserDetailViewController];
    userDetailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:userDetailVC animated:YES];
}

#pragma mark - Private Method
/** 跳转到安全设置界面 */
- (void)presentToSecurityViewController {
    MSSecurityViewController *securityVC = [[MSSecurityViewController alloc] init];
    securityVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:securityVC animated:YES];
}
/** 跳转到商家入驻界面 */
- (void)presentToBusinessEnterViewController {
    UIStoryboard *uploadInfo = [UIStoryboard storyboardWithName:@"UploadBusiness" bundle:nil];
    UIViewController *businessEnterVC = [uploadInfo instantiateInitialViewController];
    businessEnterVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController presentViewController:businessEnterVC animated:YES completion:nil];
}

/** 清除缓存 */
- (void)clearCaches {
    [self showAlertControllerWithTitle:@"您确定清除缓存？" message:@"" confirmButton:@"清除" cancelButton:@"取消" confirmClickBlock:^{
        // 清除缓存
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
            [[NSFileManager defaultManager]removeItemAtPath:cachePath error:nil];
            // 通知主线程刷新
            __weak typeof(self) weakself = self;
            dispatch_async(dispatch_get_main_queue(), ^{
                MSUserCenterCell *cell = [weakself.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:MSUserCenterCellTypeCache inSection:0]];
                if (cell) {
                    [cell clearCacheValue];
                }
            });
        });
    } cancelClickBlock:nil];
}

// 缓存大小
- (CGFloat)folderSize {
    CGFloat folderSize = 0.0;
    //获取路径
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)firstObject];
    //获取所有文件的数组
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
    NSLog(@"文件数：%ld",files.count);
    for(NSString *path in files) {
        NSString*filePath = [cachePath stringByAppendingString:[NSString stringWithFormat:@"/%@",path]];
        //累加
        folderSize += [[NSFileManager defaultManager]attributesOfItemAtPath:filePath error:nil].fileSize;
    }
    //转换为M为单位
    CGFloat sizeM = folderSize /1024.0/1024.0;
    
    return sizeM;
}
/** 联系客服 */
- (void)contactCustomerService {
    NSString *message = @"客服号码为:0898-23586161，请确认是否拨号?";
    [self showAlertControllerWithTitle:message message:@"" confirmButton:@"拨号" cancelButton:@"取消" confirmClickBlock:^{
        NSString *callPhone = @"telprompt://0898-23586161";
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone] options:@{} completionHandler:nil];
        } else {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
        }
    } cancelClickBlock:nil];
}

#pragma mark - Setter And Getter

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        
        [_tableView registerNib:[UINib nibWithNibName:@"MSUserCenterCell" bundle:nil] forCellReuseIdentifier:@"MSUserCenterCell"];
    }
    return _tableView;
}

- (UIView *)tableHeadView {
    if (!_tableHeadView) {
        CGFloat headViewHeight = 210;
        _tableHeadView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, MS_SCREEN_WIDTH, headViewHeight)];
        _tableHeadView.backgroundColor = rgba(0, 0, 0, 0.3);
        
        UIView *bufferView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, MS_SCREEN_WIDTH, headViewHeight)];
        bufferView.backgroundColor = [UIColor clearColor];
        [_tableHeadView addSubview:bufferView];
        self.bufferView = bufferView;
        
        // 头像
        CGFloat iconWidth = 60;
        CGFloat iconY = 70;
        CGFloat iconX = (MS_SCREEN_WIDTH - iconWidth) / 2.0;
        UIImageView *headIcon = [[UIImageView alloc] initWithFrame:CGRectMake(iconX, iconY, iconWidth, iconWidth)];
        headIcon.backgroundColor = [UIColor colorWithHexString:@"#FF6666"];
        headIcon.layer.cornerRadius = iconWidth / 2.0;
        headIcon.layer.masksToBounds = YES;
        [_tableHeadView addSubview:headIcon];
        self.headIcon = headIcon;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headIconClick)];
        self.headIcon.userInteractionEnabled = YES;
        [self.headIcon addGestureRecognizer:tap];
        
        // 标签
        CGFloat nameY = CGRectGetMaxY(headIcon.frame) + 12;
        CGFloat nameX = 20;
        CGFloat nameWidth = MS_SCREEN_WIDTH - 2 * nameX;
        CGFloat nameHeight = 25;
        UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(nameX, nameY, nameWidth, nameHeight)];
        nameLabel.font = [UIFont systemFontOfSize:14];
        nameLabel.textAlignment = NSTextAlignmentCenter;
        nameLabel.textColor = [UIColor whiteColor];
        [_tableHeadView addSubview:nameLabel];
        self.userNameLabel = nameLabel;
    }
    return _tableHeadView;
}

- (UIView *)tableFootView {
    if (!_tableFootView) {
        CGFloat headViewHeight = 70;
        _tableFootView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, MS_SCREEN_WIDTH, headViewHeight)];
        _tableFootView.backgroundColor = [UIColor clearColor];
        
        // 退出按钮
        CGFloat buttonWidth = MS_SCREEN_WIDTH;
        CGFloat buttonHeight = 50;
        CGFloat buttonX = 0;
        CGFloat buttonY = 10;
        UIButton *logOutButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [logOutButton setFrame:CGRectMake(buttonX, buttonY, buttonWidth, buttonHeight)];
        [logOutButton setTitle:@"退出登录" forState:UIControlStateNormal];
        [logOutButton setTitleColor:MSThemeColor forState:UIControlStateNormal];
        logOutButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [logOutButton setBackgroundColor:[UIColor whiteColor]];
        [logOutButton addTarget:self action:@selector(logOutButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [_tableFootView addSubview:logOutButton];
        
    }
    return _tableFootView;
}

- (UIButton *)mailButton {
    if (!_mailButton) {
        _mailButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_mailButton setImage:[UIImage imageNamed:@"account_mail"] forState:UIControlStateNormal];
        [_mailButton addTarget:self action:@selector(mailButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _mailButton;
}

#pragma mark -  Memory Method

- (void)dealloc {
    NSLog(@"%s", __func__);
}

@end
